﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace OkTool.Util
{
    public class AssemblyUtil
    {
      
        /// <summary>
        /// 查找子类,实现类
        /// </summary>
        /// <param name="type">父类或接口</param>
        ///  <param name="assembly">程序集</param>
        /// <returns></returns>
        public static IEnumerable<Type> ScanAssemblyBySuper(Assembly assembly, Type type)
        {

            foreach (var type1 in assembly.GetTypes())
            {
                foreach (var t in type.GetInterfaces())
                {
                    if (t == type)
                    {
                        yield return type1;
                        break;
                    }
                }
            }

        }

        /// <summary>
        /// 扫描指定程序集下所有包含指定特性的类
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<Type> ScanAssemblyByAttribute(Assembly assembly, Type attribute)
        {
            return assembly.GetTypes()
               .Where(type => type.GetCustomAttributes(attribute, true).Length > 0)
               .ToList();
        }

        /// <summary>
        /// 扫描指定程序集指定命名空间下所有包含指定特性的类
        /// </summary>
        /// <param name="assembly"></param>
        /// <param name="namespaceName"></param>
        /// <param name="attributeType"></param>
        /// <returns></returns>
        public static List<Type> ScanNameSpaceByAttribute(Assembly assembly, string namespaceName, Type attributeType)
        {
            //Assembly assembly = Assembly.GetExecutingAssembly(); // 或者根据需要获取特定的程序集
            return assembly.GetTypes()
                .Where(type => type.Namespace == namespaceName && type.GetCustomAttributes(attributeType, true).Length > 0)
                .ToList();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="assembly"></param>
        /// <param name="namespaceName"></param>
        /// <returns></returns>
        public static List<Type> ScanNameSpace(Assembly assembly, string namespaceName)
        {
            //Assembly assembly = Assembly.GetExecutingAssembly(); // 或者根据需要获取特定的程序集
            return assembly.GetTypes()
                .Where(type => type.Namespace == namespaceName)
                .ToList();
        }
    }
}
